package cn.chenmixuexi.client;

import cn.chenmixuexi.client.handler.RpcResponseMessageHandler;
import cn.chenmixuexi.message.RpcRequestMessage;
import cn.chenmixuexi.protocol.MessageCodecSharable;
import cn.chenmixuexi.protocol.ProcotolFrameDecoder;
import cn.chenmixuexi.protocol.SequenceIdGenerator;
import cn.chenmixuexi.server.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

import java.awt.*;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Slf4j
public class RpcClientManager {

    public static <T> T getProxyService(Class<T> serviceClass){
        ClassLoader classLoader = serviceClass.getClassLoader();
        Class<?>[] interfaces = new Class[]{serviceClass};
        T o = (T)Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                int sequenceId = SequenceIdGenerator.nextId();
                getChannel().writeAndFlush(new RpcRequestMessage(
                        sequenceId,
                        serviceClass.getName(),
                        method.getName(),
                        method.getReturnType(),
                        method.getParameterTypes(),
                        args));
                //                                                    参数是promise执行需要的线程池
                DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
                RpcResponseMessageHandler.PROMISES.put(sequenceId,promise);
                //等待promise结果
                promise.await();
                if(promise.isSuccess()){
                    return promise.getNow();
                }else{
                    throw new RuntimeException(promise.cause());
                }

            }
        });
        return o;
    }


    public static void main(String[] args) throws IOException {
//        RpcRequestMessage message = new RpcRequestMessage(1,
//                "cn.chenmixuexi.server.service.HelloService",
//                "sayHello",
//                String.class,
//                new Class[]{String.class},
//                new Object[]{"zhangsan"});
//        getChannel().writeAndFlush(message);
        HelloService proxyService = getProxyService(HelloService.class);
        log.debug("请求...");
        String hello = proxyService.sayHello("hello");
        log.debug("请求结束...");
        System.out.println(hello);
    }

    private static Channel channel = null;
    private static final Object LOCK = new Object();

    public static Channel getChannel(){
        if(channel!=null){
            return channel;
        }
        synchronized (LOCK){
            if(channel!=null){
                return channel;
            }
            initChannel();
            return channel;
        }
    }
    //初始化Channel方法
    public static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    System.out.println(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    System.out.println(MESSAGE_CODEC);
                    ch.pipeline().addLast(RPC_HANDLER);
                    System.out.println(RPC_HANDLER);
                }
            });
            channel = bootstrap.connect("localhost", 8080).sync().channel();

            channel.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    group.shutdownGracefully();
                }
            });
        } catch (Exception e) {
            log.error("client error", e);
        }
    }
}
